package cn.yujiago.springboot.utils;

import cn.yujiago.springboot.config.Constants;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

/**
 * Shiro工具类
 */
public class ShiroUtils {

    // 加密算法：MD5、SHA1
    private static final String Hash_Algorithm_Name = Constants.Hash_Algorithm_Name;
    // 散列次数
    private static final int Hash_Iterations = Constants.Hash_Iterations;

    /**
     * 返回使用盐值加密的SimpleAuthenticationInfo
     * @param principal              用户主体
     * @param hashedCredentials      从数据库查出的加密密码
     * @param username               用于盐值加密的用户名
     * @param realmName              所调用该方法的realm名
     * @return
     */
    public static SimpleAuthenticationInfo getSimpleAuthenticationInfo(Object principal, String hashedCredentials, String username, String realmName){
        ByteSource credentialsSalt = null;
        // 以用户名作为盐值
        if(StringUtils.isNoneBlank(username)){
            credentialsSalt = ByteSource.Util.bytes(username);
        }
        return new SimpleAuthenticationInfo(principal, hashedCredentials, credentialsSalt, realmName);
    }

    /**
     * 获得加盐加密后的密码，用于注册时获取加密密码
     * @param password  明文密码
     * @param username  用户名，作为盐值
     * @return
     */
    public static Object getSimpleHash(String password, String username){
        Object credentials = password;
        Object credentialsSalt = ByteSource.Util.bytes(username);
        return new SimpleHash(Hash_Algorithm_Name, credentials, credentialsSalt, Hash_Iterations);
    }

    public static void main(String[] args){

        Object credentials = "123456";
        Object credentialsSalt = ByteSource.Util.bytes("admin");
        System.out.println(credentialsSalt);
        Object result = new SimpleHash(Hash_Algorithm_Name, credentials, credentialsSalt, Hash_Iterations);
        System.out.println(result);

    }

}
